package com.question.business.role.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.question.business.role.entity.RoleMenu;
import com.question.business.role.mapper.RoleMenuMapper;
import com.question.business.role.service.IRoleMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色菜单服务实现类
 *
 * @author star
 * @since 2023-09-13
 */
@Slf4j
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {


    /**
     * 角色菜单查询
     *
     * @param roleId 角色ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryMenuByRoleId(String roleId) {
        return baseMapper.queryRoleMenuList(roleId);
    }

    /**
     * 角色菜单新增数据
     *
     * @param roleId  角色ID
     * @param menuIds 菜单ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRoleMenu(String roleId, List<String> menuIds) {
        // 删除角色菜单
        baseMapper.deleteByRoleId(roleId);
        if (CollectionUtils.isNotEmpty(menuIds)) {
            List<RoleMenu> data = new ArrayList<>(menuIds.size());
            for (String menuId : menuIds) {
                RoleMenu entity = new RoleMenu();
                entity.setRoleId(roleId);
                entity.setMenuId(menuId);
                data.add(entity);
            }
            super.saveBatch(data);
        }
    }

    /**
     * 角色菜单接口是否授权
     *
     * @param roles 角色ID
     * @param url   菜单接口
     * @return boolean
     */
    @Override
    public boolean isInterfaceAuth(List<String> roles, String url) {
        return SqlHelper.retBool(baseMapper.selectCountByRoleOrInterface(roles, url));
    }
}